package com.bb.blog.code.threading.example;

import com.bb.blog.code.threading.JMM;

public class VolatileVisibilityExample implements JMM {
    private Boolean initFlag = false;

    public void refresh() {
        this.initFlag = true;
        String name = Thread.currentThread().getName();
        System.out.println("线程" + name + "修改初始化变量initFlag");
    }

    public void load(){
        String name = Thread.currentThread().getName();
        while(!initFlag){
//            System.out.println("安全");
        }
        System.out.println("线程"+name+"嗅探到initFlag改变了");
    }

    public static void main(String[] args) {
        VolatileVisibilityExample example = new VolatileVisibilityExample();
        Thread threadA =  new Thread(()->{
            example.refresh();
        });
        Thread threadB = new Thread(()->{
            example.load();
        });
        threadB.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        threadA.start();
    }

}
